<template>
  <el-select v-bind="$attrs" v-on="$listeners" @visible-change="visibleChange" @change="change" clearable filterable>
    <el-option v-for="city in options" :label="city.name" :value="city.code">
      <div class="item">
        <span>{{city.name}}</span>
        <span>{{city.provinceName + (isNull(city.cityName) ? '' : ' / ' + city.cityName)}}</span>
      </div>
    </el-option>
  </el-select>
</template>

<script>
import { mapGetters } from 'vuex'
import { isNull } from '@/utils/type'

let delayLoadCityData

export default {
  data() {
    return {
      options: []
    }
  },
  computed: {
    ...mapGetters(['allCityData'])
  },
  watch: {
    '$attrs.value': {
      immediate: true,
      handler(code) {
        this.options = this.allCityData.filter(city => city.code == code)
      }
    }
  },
  methods: { isNull,
    visibleChange(visible) {
      if (visible) {
        const code = this.$attrs.value
        if (code) {
          this.options = this.allCityData.filter(city => city.code == code)
        } else {
          this.options = this.allCityData.slice(0, 16)
        }
        delayLoadCityData = setTimeout(() => {
          this.options = this.allCityData
        }, 300)
      } else {
        clearTimeout(delayLoadCityData)
        this.options = this.allCityData.slice(0, 16)
      }
    },
    change(code) {
      const selectedOptions = this.allCityData.filter(city => city.code == code)
      if (selectedOptions.length) {
        const selectedOption = selectedOptions[0]
        this.$emit('select', selectedOption)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.item { display: flex; align-items: center;
  span:last-child { margin-left: 16px; font-size: 12px; color: #888; }}
</style>